//
//  CustomTradePassword.m
//  HuoBao
//
//  Created by 于会海 on 15/12/4.
//  Copyright © 2015年 jinxin. All rights reserved.
//

#import "CustomTradePassword.h"
#import "HBLoginManager.h"
#import "CustomSuggestionAlert.h"
#import "HBUserConfirmDistillInfo.h"
#import "HBUserConfirmDistillParam.h"
#import "HBUserConfirmDistillParser.h"
#import "NSString+MKNetworkKitAdditions.h"

@interface CustomTradePassword ()<UITextFieldDelegate>
{
    UIImageView*     passCodeimage[6];
    UIView*          passView[6];
    NSString*        password;
    UITextRange*     previousSelection;
    NSString*        previousTextFieldContent;
    UILabel*         alertLabel;
    UITextField*     passField;
    int              enterCount;
    NSMutableArray*  codeImageArr;
}
@property (nonatomic, strong) void(^CancelAction)();
@property (nonatomic, strong) UIView *dangban;
@property (nonatomic, strong) UIView *bgview;
@property (nonatomic, strong) UIButton* cancelSmlBtn;
@property (nonatomic, strong) UIButton* cancelBigBtn;
@end
#define GetFinalresult(x,y) (IsIphone4?x:y)
#define GetFinalResult(x,y,z,r) (IsIphone4?x:(IsIphone6P?r:(IsIphone5?y:z)))
#define ScaleForm5To6    1.172
#define ScaleForm4To6    1.389
#define alertViewCenter  0.3898
#define alertViewW       GetFinalResult(305/ScaleForm5To6,305/ScaleForm5To6,305,305*1.104)
#define alertViewH       GetFinalResult(157/ScaleForm4To6,157/ScaleForm5To6,157,157*1.104)
#define topTitleFont        GetFinalResult(19,19,22,22)
#define topAlertLabelFont   GetFinalResult(10,10,12,12)
#define passwordH        GetFinalResult(88)
#define passwordW        GetFinalResult(90)
@implementation CustomTradePassword
@synthesize enterTradPassword;
- (instancetype)init{

    self = [super init];
    codeImageArr = [NSMutableArray arrayWithCapacity:6];
    enterCount = 0;
    self.backgroundColor = [UIColor clearColor];
    self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    self.dangban = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    self.dangban.backgroundColor = [UIColor blackColor];
    self.dangban.alpha = 0.3;
    [self addSubview:self.dangban];
    
    self.bgview = [[UIView alloc]initWithFrame:CGRectMake(35, SCREEN_HEIGHT*190/575, alertViewW, alertViewH)];
    self.bgview.center = CGPointMake(self.dangban.center.x, SCREEN_HEIGHT*alertViewCenter);
    self.bgview.backgroundColor = [LCCommon getColor:@"3d3e41"];
    self.bgview.alpha = 0;
    self.bgview.layer.cornerRadius = 4;
    [self addSubview:self.bgview];
    
    
    self.cancelSmlBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelSmlBtn.frame = CGRectMake(self.bgview.size.width -24 , 12, 12, 12);
    [self.cancelSmlBtn setBackgroundImage:[UIImage imageNamed:@"home_close"] forState:UIControlStateNormal];
    [self.bgview addSubview:self.cancelSmlBtn];
    
    self.cancelBigBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.cancelBigBtn.frame = CGRectMake(self.bgview.size.width -30 , 10, 30, 30);
    [self.cancelBigBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self.bgview addSubview:self.cancelBigBtn];
    [self.cancelBigBtn addTarget:self action:@selector(cancelBigBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel* topTitle = [self LabelWithRect:CGRectMake(30, 15, self.bgview.size.width-60, 25) textColor:[LCCommon getColor:@"ffffff"] textstr:@"请输入提现密码" textfont:22 textstyle:NSTextAlignmentCenter];
    [self.bgview addSubview:topTitle];
    
    alertLabel = [self LabelWithRect:CGRectMake(20, GetFinalresult(40, 50), self.bgview.size.width-40, 20) textColor:[LCCommon getColor:@"f24545"] textstr:@"" textfont:12 textstyle:NSTextAlignmentCenter];
    [self.bgview addSubview:alertLabel];
    
    UIView* botView = [[UIView alloc] initWithFrame:CGRectMake(GetFinalResult(10,10,15,15),GetFinalResult(70, 70, 82, 82), (alertViewW*45/305)*6+5, alertViewH*44/157)];
    [botView setBackgroundColor:[LCCommon getColor:@"2e2f35"]];
    [self.bgview addSubview:botView];
    
    CGFloat xLeft = 1;
    for (int i=0; i<6; i++) {
        passView[i] = [[UIView alloc] initWithFrame:CGRectMake(0, 0, alertViewW*45/305,alertViewH*44/157)];
        [passView[i] setBackgroundColor:[LCCommon getColor:@"999999"]];
        passView[i].frame = CGRectOffset(passView[i].frame, xLeft, 0);
        [botView addSubview:passView[i]];
        xLeft += 1 + passView[i].frame.size.width;

        passCodeimage[i] =[[UIImageView alloc] initWithFrame:CGRectMake(0,0,10,10)];
        [passCodeimage[i] setHidden:YES];
        [passCodeimage[i] setCenter:CGPointMake(alertViewW*45/(305*2), alertViewH*44/(157*2))];
        LLog(@"%lf",passCodeimage[i].frame.origin.y);
        [passCodeimage[i] setImage:[UIImage imageNamed:@"passcode"]];
        [codeImageArr addObject:passCodeimage[i]];
        [passView[i] addSubview:passCodeimage[i]];
    }

    passField = [[UITextField alloc] initWithFrame:CGRectMake(passView[1].frame.origin.x, passView[1].frame.origin.y, passView[1].frame.size.width*6+5, 44)];
    passField .autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
    passField .borderStyle = UITextBorderStyleNone;
    passField .secureTextEntry = YES;
    passField .keyboardType = UIKeyboardTypeNumberPad;
    [passField  addTarget:self action:@selector(passwordBackView:) forControlEvents:UIControlEventEditingChanged];
    [self.bgview addSubview:passField];
    [passField setHidden:YES];
    [passField setDelegate:self];
    [passField becomeFirstResponder];
    
    return self;
}

- (void)cancelBigBtnClicked:(UIButton*) button{
    LLog(@"取消");
    [self removeFromSuperview];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    previousTextFieldContent = textField.text;
    previousSelection = textField.selectedTextRange;
    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    NSString * toBeString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if ([toBeString length] > 6) {
        return NO;
    }
    if ((5-enterCount) == 0) {
        return NO ;
    }
    return YES;
}

- (void)passwordBackView:(UITextField*)textfield{
    alertLabel.text = @"";
    NSString *text = passField.text;
    //第几次输入
    NSUInteger targetCursorPosition =[textfield offsetFromPosition:textfield.beginningOfDocument toPosition:textfield.selectedTextRange.start];
    
    NSString* nStr = textfield.text;
    NSString* preTxt = [previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    char editFlag = 0;
    if (nStr.length <= preTxt.length) {
        editFlag = 0;
        UIImageView* imageView = passCodeimage[targetCursorPosition];
        LLog(@"删除第%li个密码",(long)targetCursorPosition);
        imageView.hidden = YES;
    }else {
        UIImageView* imageView = passCodeimage[targetCursorPosition-1];
        editFlag = 1;
        LLog(@"增加第%li个密码",(long)targetCursorPosition);
        imageView.hidden = NO;
    }
    if ([text length] == 6) {
        if (self.enterTradPassword)
        {
            self.enterTradPassword(passField.text);
        }
        [self requestToCheckTradPasswordWithPsw:passField.text];
    }
}

- (void)requestToCheckTradPasswordWithPsw:(NSString*)tradingPwd{
    HBUserConfirmDistillParam* param = [[HBUserConfirmDistillParam alloc] init];
    HBUserConfirmDistillParser* parser = [[HBUserConfirmDistillParser alloc] init];
    param.uid = [HBLoginManager sharedHBLoginManager].currentUserInfo.uid;
    param.token = [HBLoginManager sharedHBLoginManager].currentUserInfo.token;
    param.distillMoney = self.distillMoney;
    param.tradingPwd = tradingPwd.md5;
    
    [NetCenter postDataFromURL:Method_userConfirmDistill params:param parser:parser result:^(ParserResult *myResult) {
        if (myResult.code == 0) {
            HBUserConfirmDistillInfo* info = (HBUserConfirmDistillInfo*)myResult.result;
            if ([info.distillStatus isEqualToString:@"0"]) {
                LLog( @"提现申请成功");
                if (self.isSuccess) {
                    [self removeFromSuperview];
                    self.isSuccess(YES,info,myResult.message);
                }
            }else if([info.distillStatus isEqualToString:@"1"]){
                LLog(@"提现申请失败");
                if (self.isSuccess) {
                    [self removeFromSuperview];
                    self.isSuccess(NO,info,myResult.message);

                }
            }
        }else if(myResult.code == 1){
            LLog(@"交易密码错误");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                enterCount++;
                alertLabel.text = myResult.message;
                passField.text = @"";
                [self allPasswordEmpty];
                LLog(@"输入了密码---%@",passField.text);
                if ((5-enterCount) == 0) {
                    if (self.pswError) {
                        [self removeFromSuperview];
                        self.pswError(NO);
                    } 
                }
            });

        }else if(myResult.code == 2){
            if (self.pswError) {
                [self removeFromSuperview];
                self.pswError(NO);
            }
        }
    } failure:^(NSError *error) {
        DISSMISS_ERR(error.description);
    }];
}

- (void)allPasswordEmpty{
    for (UIImageView* imageView in codeImageArr) {
        [imageView setHidden:YES];
    }
}

-(UILabel *)LabelWithRect:(CGRect)rect textColor:(UIColor *)color textstr:(NSString *)str textfont:(int)font textstyle:(NSTextAlignment)aligment{
    UILabel *label = [[UILabel alloc] initWithFrame:rect];
    label.textColor = color;
    label.text = str;
    label.font = [UIFont systemFontOfSize:font];
    label.textAlignment = aligment;
    label.numberOfLines = 0;
    return label;
}

-(void)makeLinewithRect:(CGRect)rect Color:(UIColor *)color addview:(UIView *)vi{
    UIView *line = [[UIView alloc]initWithFrame:rect];
    line.backgroundColor = color;
    [vi addSubview:line];
}

- (void)dismissTradPswAlertView{
    [self removeFromSuperview];
}

- (void)showTradPasswordAlertView{
    [UIView animateWithDuration:0.25 animations:^{
        self.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        self.bgview.backgroundColor = [LCCommon getColor:@"3d3e41"];
        self.bgview.alpha = 1;
    }completion:^(BOOL finished) {
        
    }];
}

- (void)showAlertWithString:(NSString *)alertString{
    
    alertLabel.text = alertString;
    [self allPasswordEmpty];
    //测试用
    passField.text = @"";
}

@end
